package playing.action;

import object.Plant;
import playing.PlantDataReader;
import playing.PlayerPlantReading;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Timestamp;
import java.util.Date;

public class add {
    private int userId;

    public add(int id) {
        this.userId = id;

        JFrame frame = new JFrame("创建植物");
        frame.setSize(400, 200);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setLocationRelativeTo(null);

        JPanel panel = new JPanel(new GridLayout(3, 1));

        JLabel label = new JLabel("请输入要创建的植物的名字:");
        JTextField textField = new JTextField();

        JButton createButton = new JButton("创建");

        panel.add(label);
        panel.add(textField);
        panel.add(createButton);

        frame.add(panel);
        frame.setVisible(true);

        createButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String plantName = textField.getText();

                if (new PlantDataReader().isPlantNameExists(plantName)) {
                    JOptionPane.showMessageDialog(frame, "创建失败名称重复，请重新创建", "错误", JOptionPane.ERROR_MESSAGE);
                } else {
                    Date now = new Date();
                    Timestamp timestamp = new Timestamp(now.getTime());

                    Plant newPlant = new Plant(0, plantName, timestamp);
                    new PlantDataReader().savePlant(newPlant);
                    new PlayerPlantReading().insertPlantForUser(userId, new PlantDataReader().getPlantIdByName(plantName));

                    JOptionPane.showMessageDialog(frame, "创建成功, 你创建的植物id是" + new PlantDataReader().getPlantIdByName(plantName), "成功", JOptionPane.INFORMATION_MESSAGE);
                }
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new add(1);  // 假设用户ID为1
            }
        });
    }
}
